package com.keyin.android.util;

import java.lang.reflect.Field;

import org.json.JSONObject;


public class ReflectionFactory {

	public static Object create(JSONObject j, Class<?> c) throws Exception {

		Object obj = c.newInstance();

		Field[] fields = c.getFields();
		for (Field f : fields) {
			String typeName = f.getType().getName();
			String jsonKey = f.getName();

			try {
				if (typeName.equals("boolean")) {
					f.setBoolean(obj, j.getBoolean(jsonKey));
				} else if (typeName.equals(Boolean.class.getName())) {
					f.setBoolean(obj, new Boolean(jsonKey));
				} else if (typeName.equals("int") || typeName.equals("byte")) {
					f.setInt(obj, j.getInt(jsonKey));
				} else if (typeName.equals(Integer.class.getName())
						|| typeName.equals(Byte.class.getName())) {
					f.setInt(obj, new Integer(j.getInt(jsonKey)));
				} else if (typeName.equals(String.class.getName())) {
					f.set(obj, j.getString(jsonKey));
				} else if (typeName.equals("double")
						|| typeName.equals("float")) {
					f.setDouble(obj, j.getInt(jsonKey));
				} else if (typeName.equals(Double.class.getName())
						|| typeName.equals(Float.class.getName())) {
					f.setDouble(obj, new Double(j.getInt(jsonKey)));
				} else if (typeName.equals("long")) {
					f.setLong(obj, j.getInt(jsonKey));
				} else if (typeName.equals(Long.class.getName())) {
					f.setLong(obj, new Long(j.getInt(jsonKey)));
				}
			} catch (Exception e) {
				continue;
			}
		}

		return obj;
	}

	public static Object create(JSONObject j, String className)
			throws Exception {

		return create(j, Class.forName(className));
	}
}
